<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
	<div class="min-h-screen bg-gray-50">
		<!-- 上传区域 -->
		<div class="container mx-auto px-6 py-8">
			<h1
				class="flex items-center text-4xl font-bold bg-gradient-to-r from-blue-600 to-blue-800 bg-clip-text text-transparent mb-8">
				<i class="fas fa-chart-network mr-3"></i>
				JBoltAI智能竞品分析
				<span class="ml-3 text-lg text-gray-500 font-normal">Professional Competition Analysis </span>
			</h1>
			<!-- 文件上传区域 -->
			<div class="bg-white rounded-lg shadow-md p-8 mb-8">
				<div class="border-2 border-dashed border-blue-300 rounded-lg p-8 text-center cursor-pointer hover:border-blue-500 transition-colors"
					:class="{ 'bg-blue-50': isDragging }" @dragenter.prevent="isDragging = true"
					@dragleave.prevent="isDragging = false" @dragover.prevent @drop.prevent="handleFileDrop"
					@click="triggerFileInput">
					<i class="fas fa-cloud-upload-alt text-4xl text-blue-500 mb-4"></i>
					<h3 class="text-xl font-semibold mb-2">拖拽文件到此处或点击上传</h3>
					<p class="text-gray-500">支持 PDF、DOCX 等多种文件格式（最多2个文件,一个文件只能包含一种产品）</p>
					<input type="file" ref="fileInput" class="hidden" multiple @change="handleFileSelect">
				</div>
				<!-- 已上传文件列表 -->
				<div v-if="uploadedFiles.length > 0" class="mt-6">
					<h4 class="text-lg font-semibold mb-4">已上传文件</h4>
					<div class="space-y-3">
						<div v-for="(file, index) in uploadedFiles" :key="index"
							class="flex items-center justify-between bg-gray-50 p-3 rounded">
							<div class="flex items-center">
								<i class="fas fa-file-alt text-blue-500 mr-3"></i>
								<span>{{ file.name }}</span>
							</div>
							<button @click="removeFile(index)" class="text-red-500 hover:text-red-700">
								<i class="fas fa-times"></i>
							</button>
						</div>
					</div>
				</div>
				<!-- 分析按钮 -->
				<div class="mt-8 text-center space-x-4">
					<button @click="loadSampleData"
						class="!rounded-button bg-gray-500 text-white px-8 py-3 text-lg font-semibold hover:bg-gray-600 transition-colors whitespace-nowrap">
						<i class="fas fa-database mr-2"></i>
						案例数据
					</button>
					<button @click="startAnalysis"
						class="!rounded-button bg-blue-600 text-white px-8 py-3 text-lg font-semibold hover:bg-blue-700 transition-colors whitespace-nowrap"
						:disabled="uploadedFiles.length === 0 || isAnalyzing">
						<i class="fas fa-chart-line mr-2"></i>
						{{ isAnalyzing ? '分析中...' : '开始分析' }}
					</button>
				</div>
			</div>
			<!-- 分析结果展示区域 -->
			<div v-if="showResults" class="bg-white rounded-lg shadow-md p-8">
				<!-- Tab导航 -->
				<div class="border-b mb-6">
					<div class="flex space-x-6">
						<button v-for="tab in tabs" :key="tab.id" @click="currentTab = tab.id"
							class="pb-3 px-2 font-medium whitespace-nowrap"
							:class="currentTab === tab.id ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-500 hover:text-gray-700'">
							<i :class="tab.icon + ' mr-2'"></i>
							{{ tab.name }}
						</button>
					</div>
				</div>
				<!-- 图表展示区域 -->
				<div class="grid grid-cols-2 gap-8">
					<!-- 雷达图 -->
					<div class="bg-gray-50 rounded-lg p-6">
						<h3 class="text-lg font-semibold mb-2">{{productAName}}</h3>

						<div class="mt-2 text-gray-600 space-y-2">
							<p class="flex items-start">
								<i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
								<span>{{showProductADdesc(currentTab)}}</span>
							</p>
						</div>
					</div>
					<!-- 柱状图 -->
					<div class="bg-gray-50 rounded-lg p-6">
						<h3 class="text-lg font-semibold mb-2">{{productBName}}</h3>

						<div class="mt-2 text-gray-600 space-y-2">
							<p class="flex items-start">
								<i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
								<span>{{showProductBDdesc(currentTab)}}</span>
							</p>

						</div>
					</div>
				</div>
				<!-- 详细分析表格 -->
				<div class="mt-8">
					<h3 class="text-lg font-semibold mb-4">详细分析</h3>
					<div class="overflow-x-auto">
						<table class="min-w-full divide-y divide-gray-200">
							<thead>
								<tr>
									<th
										class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
										评估维度</th>
									<th
										class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
										{{productAName}}
									</th>
									<th
										class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
										{{productBName}}
									</th>

								</tr>
							</thead>
							<tbody class="bg-white divide-y divide-gray-200">
								<tr v-for="(item, index) in analysisData" :key="index">
									<td class="px-6 py-4 whitespace-nowrap">{{ item.dimension }}</td>
									<td class="px-6 py-4"
										:style="item.productAScore > item.productBScore? 'color: red' : ''">
										{{ item.productAScore }}
									</td>
									<td class="px-6 py-4"
										:style="item.productBScore > item.productAScore? 'color: red' : ''">
										{{ item.productBScore }}
									</td>

								</tr>
							</tbody>
						</table>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script lang="ts" setup>
	import * as echarts from 'echarts';
	import { useMessage } from 'naive-ui'
	import { ref, onMounted, computed, watch, reactive } from 'vue';
	import { JBoltApi } from '@/service/request'
	import { useWebSocketStore } from "@/stores/websocket.js";
	import { storeToRefs } from "pinia";
	import AiChat from '@/components/_builtin/jb-ai-chat/index.js'

	const message = useMessage()
	const webSocketStore = storeToRefs(useWebSocketStore())
	const chatContainer = ref(null)
	const chatInstance = ref(null)
	const currentSession = ref({})	//默认当前的session对象
	const chartContainer = ref<HTMLElement | null>(null);
	const resumes = ref([]);
	const showDetailModal = ref(false);
	const fileUrl = ref("");
	const productAName = ref("产品A")
	const productBName = ref("产品B")
	const isDragging = ref(false);//默认false.不是案例
	const isExample = ref(false);
	const fileInput = ref<HTMLInputElement | null>(null);
	const uploadedFiles = ref<File[]>([]);
	const uploadedFileUrlList = ref<String[]>([])
	const isAnalyzing = ref(false);
	const showResults = ref(false);
	const currentTab = ref('features');
	const radarChart = ref<HTMLElement | null>(null);
	const barChart = ref<HTMLElement | null>(null);
	const tabs = ref([]);
	const analysisData = ref([]);
	const triggerFileInput = () => {
		fileInput.value?.click();
	};


	watch(() => webSocketStore.ws.value, () => {
		console.debug("websock重连")
		if (chatInstance.value) {
			chatInstance.value.updateWebSocket(webSocketStore.ws.value)
		}
	})

	watch(() => chatContainer.value, (newV) => {
		if (newV && !chatInstance.value) {
			loadChatInstance()
		}
	})
	watch(() => useWebSocketStore().ws.value, (newV) => {

		if (chatContainer.value && newV) {
			chatInstance.value.updateWebSocket(useWebSocketStore().ws.value)
		}
	})
	const loadSampleData = () => {
		uploadedFiles.value = [
			new File(["sample content 1"], "sample_file_1.pdf", { type: "application/pdf" }),
			new File(["sample content 2"], "sample_file_2.docx", { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" })
		];
		isExample.value = true;//是案例

	};

	const handleFileSelect = (event : Event) => {
		const target = event.target as HTMLInputElement;
		if (target.files && target.files[0]) {
			const newFiles = Array.from(target.files);
			const totalFiles = uploadedFiles.value.length + newFiles.length;
			console.log(totalFiles);
			if (totalFiles > 2) {
				message.error('最多只能上传2个文件');
				return;
			}
			for (const file of newFiles) {
				uploadFile(file);
			}

		}

	};
	const handleFileDrop = (event : DragEvent) => {

		isDragging.value = false;
		const files = event.dataTransfer?.files;
		if (files) {
			const newFiles = Array.from(files);
			const totalFiles = uploadedFiles.value.length + newFiles.length;
			if (totalFiles > 2) {
				alert('最多只能上传2个文件');
				return;
			}
			uploadFile(newFiles);
		}
	};

	function uploadFile(file) {
		JBoltApi.uploadToQiniu(file, "/ndemo/report_helper/{date(yyyyMMddHHmm)}/{random(6)}.{oriSuffix}", '', null, (res) => {
			console.log("上传成功：", res)
			uploadedFiles.value.push(file);
			uploadedFileUrlList.value.push(res.url)
			// uploadedFiles.value = [...uploadedFiles.value, ...file];
			// uploadedFileUrlList.value = [...uploadedFileUrlList.value, res.url];
			console.log(uploadedFiles.value);
			console.log(uploadedFileUrlList.value);
		})
		return;
	}
	const removeFile = (index : number) => {
		uploadedFiles.value.splice(index, 1);
		uploadedFileUrlList.value.splice(index, 1);
	};
	const startAnalysis = async () => {
		if (uploadedFiles.value.length != 2) {
			message.error("一次只可以分析两个文件哦~");
			return;
		} else {
			if (isExample.value == true) {//案例
				submitExample();
			} else {
				submitProduct();
			}
		}
	};

	function submitExample() { //提交案例
		isExample.value = false;
		showResults.value = true;
		tabs.value = [{
			id: 'features', name: '功能与性能', icon: 'fas fa-cogs',
			'productADesc': '采用先进的微服务架构，系统性能出色，服务响应时间平均低于 100ms',
			'productBDesc': '内置智能负载均衡算法，可支持 10,000+ 并发用户访问，系统稳定性达 99.99%'

		},
		{
			id: 'experience', name: '用户体验', icon: 'fas fa-user-check',
			'productADesc': '采用先进的微服务架构，系统性能出色，服务响应时间平均低于 100ms',
			'productBDesc': '内置智能负载均衡算法，可支持 10,000+ 并发用户访问，系统稳定性达 99.99%'

		},
		{
			id: 'price', name: '价格与性价比', icon: 'fas fa-tags',
			'productADesc': '采用先进的微服务架构，系统性能出色，服务响应时间平均低于 100ms',
			'productBDesc': '内置智能负载均衡算法，可支持 10,000+ 并发用户访问，系统稳定性达 99.99%'

		},
		{

			id: 'brand', name: '品牌与口碑', icon: 'fas fa-crown',
			'productADesc': '采用先进的微服务架构，系统性能出色，服务响应时间平均低于 100ms',
			'productBDesc': '内置智能负载均衡算法，可支持 10,000+ 并发用户访问，系统稳定性达 99.99%'

		},
		{

			id: 'service', name: '售后服务', icon: 'fas fa-headset',
			'productADesc': '采用先进的微服务架构，系统性能出色，服务响应时间平均低于 100ms',
			'productBDesc': '内置智能负载均衡算法，可支持 10,000+ 并发用户访问，系统稳定性达 99.99%'

		}];
		analysisData.value = [
			{ dimension: '功能与性能', productAScore: '95分', productBScore: '88分' },
			{ dimension: '用户体验', productAScore: '92分', productBScore: '94分' },
			{ dimension: '价格与性价比', productAScore: '90分', productBScore: '85分' },
			{ dimension: '品牌与口碑', productAScore: '88分', productBScore: '92分' },
			{ dimension: '售后服务', productAScore: '96分', productBScore: '90分' },
		]
		productAName.value = "产品A_" + uploadedFiles.value[0].name;
		productBName.value = "产品B_" + uploadedFiles.value[1].name;
	}
	function submitProduct() { //真是数据
		console.log("提交数据");

		isAnalyzing.value = true;
		showResults.value = false;
		productAName.value = "产品A_" + uploadedFiles.value[0].name;
		productBName.value = "产品B_" + uploadedFiles.value[1].name;
		let files = [
			{ 'name': productAName.value, "url": uploadedFileUrlList.value[0], sn: "productA" },
			{ 'name': productBName.value, "url": uploadedFileUrlList.value[1], sn: "productB" },
		]
		submit(files);
		console.log(productAName.value);
	}

	//提交竞品回调
	const submit = (files) => {
		console.log("请求");
		chatInstance.value.sendMessage({
			action: 'request',
			data: {
				role: 'user',
				content: { "text": '' },
				files: JSON.stringify(files)
			}
		})
	}
	//添加会话
	function addSession() {
		JBoltApi.post('/aiAppSession/add', {
			name: '新的 竞品分析 会话',
			appId: import.meta.env.VITE_APP_ID,

		}).then((res) => {
			currentSession.value = res.result.data;
			loadChatInstance();
		});
	}
	const showProductADdesc = (tabId) => {
		// 使用 find 方法查找 tabId 对应的 tab 对象
		const foundTab = tabs.value.find(tab => tab.id === tabId);
		return foundTab.productADesc;
	}
	const showProductBDdesc = (tabId) => {
		// 使用 find 方法查找 tabId 对应的 tab 对象
		const foundTab = tabs.value.find(tab => tab.id === tabId);
		return foundTab.productBDesc;
	}

	function loadChatInstance() {
		//初始化aichat
		chatInstance.value = new AiChat(chatContainer.value, {
			// websocketUrl: 'ws://192.168.31.118:8013/ws',
			websocketInstance: webSocketStore.ws.value,
			app: import.meta.env.VITE_APP_ID,
			sessionId: currentSession.value.id,
			global: null,
			onMsgSend: (msg) => {
			},
			onMsgReceive: (data) => {
				fileUrl.value = "";
				if (data.action == 'response') {
					isAnalyzing.value = false;
					try {

						let productList = JSON.parse(data.data.content.text);
						console.log(productList);
						tabs.value = productList.tabs;
						analysisData.value = productList.analysisData;
						message.success("竞品分析成功!");
						showResults.value = true;

					} catch (e) {
						message.error("竞品分析失败,请重新上传!");
					}
				}
				if (data.action == 'error') {
					isAnalyzing.value = false;
					message.error("竞品分析失败,请重新上传!");
				}
			}
		})
	}
	onMounted(() => {
		addSession();

	});
</script>
<style scoped>
	.container {
		max-width: 1440px;
	}
</style>